package com.hzk.exception;

import com.hzk.vo.RespBean;
import com.hzk.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLNonTransientException;

//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice(basePackages = "com.hzk.controller")
@Slf4j
public class GabalExceptionHandle {

    //处理JSR303数据校验抛出的异常
    /*@ExceptionHandler(Exception.class)*/
    public RespBean handleValidException(Exception e) {
        if (e instanceof GabalException) {
            GabalException ex = (GabalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        }
        if (e instanceof SQLNonTransientException) {
            SQLNonTransientException ex = (SQLNonTransientException) e;
            return RespBean.error(RespBeanEnum.SECKILL_INTERT_ERROR,ex.getMessage());
        }
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBean.setMessage("参数校验异常：" + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}

